<?php

namespace app\leader\controller;

use app\common\controller\AdminBase;
use app\common\model\Agent;
use app\common\model\AuthRoleUser;
use app\common\model\LoginUsers;
use app\common\model\WxOpen;
use think\Session;
use Wechat\Wxobjopen;

class Agents extends AdminBase
{
    public function agentlist()
    {
        $model = new Agent();
        $map['id']=array('in',$this->getagentlist());
        $agentlist = $model->where($map)->Relation('LoginUsers')->paginate('10');
        $this->assign('agentlist', $agentlist);
        return $this->fetch();
    }

    public function open_auth()
    {
        $request = request();
        $System = new \app\common\model\System();
        $Agent = new Agent();
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => request()->param('id')))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
        );
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();
        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("agents/open_auth", $_GET);
            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {
            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
            $auther['component_appid'] = $config['component_appid'];
            $auther['authorizer_appid'] = $auth_appid;
            $auther_info = $weObj->get_auther_info($auther);
            if ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3)) {
                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
                $data['alias'] = $auther_info['authorizer_info']['alias'];
                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);
                $data['authorizer_appid'] = $auth_appid;
                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                $data['at_addtime'] = time();
                $data['at_expires_in'] = 7000;
                $data['addtime'] = time();
                $data['zt'] = 1;
                $func_info = "";
                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                    $func_info .= $v['funcscope_category']['id'] . ',';
                }
                $WxOpen = new WxOpen();
                $data['func_info'] = $func_info;
                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();
                if ($wx_open) {
                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
                    $da2['wx_open_id'] = $wx_open['id'];
                } else {
                    $sj = $WxOpen->save($data);
                    $da2['wx_open_id'] = $WxOpen->id;
                }
                $da2['auth_type'] = 1;
                $mss['id'] = request()->param('id');
                $Agent = new Agent();
                $Agent->save($da2, $mss);
                if ($sj) {
                    $this->success('授权成功', url("agents/machinfo") . "?id=" . request()->param('id'));
                } else {
                    $this->error('授权失败');
                }
            } else {
                $this->error('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
            }

        }
    }

    public function agentadd()
    {
        $request = request();
        if (Request()->isPost()) {
            $arr = $request->post();
            $LoginUsers = new LoginUsers();
            //时间
//            $times=explode(" - ",$arr['times']);


            $data['username'] = trim($arr['username']);
            $data['xingming'] = trim($arr['name']);
            $data['level'] = 2001;
            $data['is_agent'] = 1;
            $data['password'] = md5($arr['password']);
            $data['tel'] = trim($arr['tel']);
            $data['createtime'] = time();
            $data['Agent'] = array(
                'name' => trim($arr['name']),
                'open_url' => trim($arr['open_url']),
                'component_appid' => trim($arr['component_appid']),
                'component_appsecret' => trim($arr['component_appsecret']),
                'component_encodingaeskey' => trim($arr['component_encodingaeskey']),
                'component_token' => trim($arr['component_token']),
                'requestdomain' => trim($arr['requestdomain']),
                'wsrequestdomain' => trim($arr['wsrequestdomain']),
                'uploaddomain' => trim($arr['uploaddomain']),
                'downloaddomain' => trim($arr['downloaddomain']),
                'webviewdomain' => trim($arr['webviewdomain']),
                'contacts' => trim($arr['contacts']),
                'tel' => trim($arr['tel']),
                'appid' => $arr['appid'],
                'appsecret' => $arr['appsecret'],
                'partnerid' => $arr['partnerid'],
                'partnerkey' => $arr['partnerkey'],
                'ali_app_id' => $arr['ali_app_id'],     //支付宝
                'ali_app_key' => $arr['ali_app_key'],
                'cmmb_mch_id' => $arr['cmmb_mch_id'],        //民生
                'cmmb_key' => $arr['cmmb_key'],
                'sys_service_provider_id' => $arr['sys_service_provider_id'],
                'apiclient_key' => $arr['key'],
                'apiclient_cert' => $arr['cert'],
                'rootca' => $arr['rootca'],
                'address' => trim($arr['address']),
                'statu' => 1,
                'sysid' => Session::get('sysloginid'),
                'addtime' => time(),
            );
            $data['Agent']['start_time']=strtotime($arr['start_time']);
            $data['Agent']['end_time']=strtotime($arr['end_time']);
//            $data['Agent']['times'] = $arr['times'];
            $add = $LoginUsers->together('Agent')->validate(true)->save($data);
            if ($add) {
                $sdata['role_id'] = 2;
                $sdata['user_id'] = $LoginUsers->id;
                $AuthRoleUser = new AuthRoleUser();
                $AuthRoleUser->save($sdata);
                //             addlog(0, "添加代理商资料".$arr['username'], "system");
                $this->success('添加成功', 'agents/agentlist');
            } else {
                $this->error($LoginUsers->getError());
            }
        } else {
            $time['starttime'] = date("Y-m-d h:i",time());
            $time['endtime'] = date("Y-m-d h:i",strtotime("+1 year"));
            $this->assign('time',$time);
            return $this->fetch();
        }
    }

    //详情
    public function agentinfo($id)
    {
        $Agent = new Agent();
        $LoginUsers = new LoginUsers();
        $map['id'] = $id;
        $agentinfo = $Agent->Relation('LoginUsers')->where($map)->find();
        $agentinfo['ticketurl'] = "https://" . $agentinfo['open_url'] . "/index.php/Wxauth/ticket/id/" . $id;
        $agentinfo['msgurl'] = "https://" . $agentinfo['open_url'] . "/api.php/id/" . $id . "/appid/\$APPID$";
        $WxOpen = new WxOpen();
        $wxopen = $WxOpen->where('id', $agentinfo['wx_open_id'])->find();
        $this->assign('wxopen', $wxopen);
        $this->assign('agentinfo', $agentinfo);
        return $this->fetch();
    }

    public function agentxg($id)
    {
        $request = request();
        if (Request()->isPost()) {
            $arr = $request->post();
            $LoginUsers = new LoginUsers();
            $Agent = new Agent();
            $data = $arr;
            //时间
            $data['start_time']=strtotime($arr['start_time']);
            $data['end_time']=strtotime($arr['end_time']);
            $data['name'] = trim($arr['name']);
            $data['contacts'] = trim($arr['contacts']);
            $data['tel'] = trim($arr['tel']);
            $data['address'] = trim($arr['address']);
//            $data['tpl_msg_type'] = $arr['tpl_msg_type'];       //通知公众号类型
            $add = $Agent->allowField(true)->validate()->save($data, ['id' => $id]);
            if ($add !== false) {
                $uid = $Agent->where('id', $id)->value('uid');
//                $datas['username'] = trim($arr['username']);
                $datas['xingming'] = trim($arr['name']);
//                if ($arr['password'] !== '') {
//                    $datas['password'] = md5($arr['password']);
//                }
                $datas['tel'] = trim($arr['tel']);
                $LoginUsers->allowField(true)->save($datas, ['id' => $uid]);
                $this->success('修改成功','agents/agentlist');
            } else {
                $this->error('修改失败');
            }
        } else {
            $Agent = new Agent();
            $LoginUsers = new LoginUsers();
            $map['id'] = $id;
            $agentinfo = $Agent->where($map)->find();
            $user = $LoginUsers->where('id', $agentinfo['uid'])->find();
            $agentinfo['start_time'] = date("Y-m-d",$agentinfo['start_time']);
            $agentinfo['end_time'] = date("Y-m-d",$agentinfo['end_time']);

            $this->assign('agentinfo', $agentinfo);
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    public function delagent()
    {
        $request = request();
        $Agent = new Agent();
        $LoginUsers = new LoginUsers();
        $id = $request->param('id');
        $cx = Agent::get($id);
        $del = $cx->together('LoginUsers')->delete();
        if ($del) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //重置密码
    public function resetpassword(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $LoginUsers = new LoginUsers();
            $password = $this->getrandmopassword(8);
            $data['password'] = MD5($password);
            $res = $LoginUsers->allowField(true)->save($data,array('username'=>$arr['username']));
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = '重置成功';
                $rarr['username'] = $arr['username'];
                $rarr['new_password'] = $password;
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '重置失败';
            }
            return json($rarr);
        }
    }

    //生成随机密码
    private function getrandmopassword($len, $chars=null){
        if (is_null($chars)){
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }


    public function is_agent()
    {
        if (Request()->isAjax()) {
            $request = request();
            $Agent = new Agent();
            $arr = $request->post('agentname');
            $map['name'] = trim($arr);
            $agent = $Agent->where($map)->count();
            if ($agent > 0) {
                $data = 0;
            } else {
                $data = 1;
            }
            return json($data);
        }
    }

    public function is_user()
    {
        if (Request()->isAjax()) {
            $request = request();
            $arr = $request->post();
            $LoginUsers = new LoginUsers();
            $map['username'] = trim($arr['username']);
            $user = $LoginUsers->where($map)->count();
            if ($user > 0) {
                $data = 0;
            } else {
                $data = 1;
            }
            return json($data);
        }
    }

    public function generate_rand()
    {
        if (request()->isAjax()) {
            $num=request()->post('num');

            return generate_rand($num);
        }
    }
}
